package com.itheima.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domin.entity.UserLoginA;
import com.itheima.domin.pojo.EmpExp;
import com.itheima.domin.query.EmpQuery;
import com.itheima.domin.pojo.Emp;
import com.itheima.domin.vo.PageResult;
import com.itheima.exception.ClientException;
import com.itheima.mapper.EmpExpMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.service.EmpService;
import com.itheima.utils.AliyunOSSOperator;
import com.itheima.utils.LoginJWTkey;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.print.Doc;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 员工业务实现
 *
 * @Author:上官徵羽
 * @Date: 2025/07/11 15:25
 * @Description TODO 今日内容:
 */
@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExpMapper empExpMapper;
    @Autowired
    private AliyunOSSOperator AOOS;

    /**
     * 批量删除员工
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmp(List<Integer> ids){
        if (ids!=null) {
            // 删除阿里云员工头像
            List<String> keys = empMapper.selectImage(ids);
            //创建工具类的对象
            empMapper.deleteEmp(ids);
            empExpMapper.deleteEmp(ids);
            //非空判断
            if (CollUtil.isNotEmpty(keys)) {
                try {
                    AOOS.deleteByUrls(keys);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 查询全部员工
     * @return
     */
    @Override
    public List<Emp> select() {
        return empMapper.select();
    }

    /**
     * 分页查询
     */
    @Override
    public PageResult<Emp> pageQuery(EmpQuery empQuery) {
        //总条数
        //Long total = empMapper.count();
        //当前页集合
        //Integer start = (page-1) * pageSize;
        //List<Emp> rows = empMapper.pageQuery(start,pageSize);
        //return new PageResult<>(empQuery);
        PageHelper.startPage(empQuery.getPage(), empQuery.getPageSize());
        Page<Emp> p = empMapper.findCondition(empQuery);
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    /**
     * 员工数据回显
     * @param id
     * @return
     */
    @Override
    public Emp selectIdEmp(Integer id){
        return empMapper.selectIdEmp(id);
    }

    /** 登录 */
    @Override
    public UserLoginA empLogin(String username, String password) {
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            throw new ClientException("用户名或密码不能为空");
        }
        try {
            //通过用户名查找员工信息,如果没找到,直接返回报错
            Emp emp = empMapper.selectUserNameEmp(username);
            log.info("EmpServiceImpl empLogin:搜寻到的员工信息{}",emp);
            //从找到的员工信息中取得密码与请求到的密码的值相比较
            if (!StrUtil.equals(emp.getPassword(),password)){
                throw new ClientException("用户名或密码错误");
            }
            String key = LoginJWTkey.testEmpJwt(username, emp.getId());
            return new UserLoginA(emp.getId(),emp.getUsername(),emp.getName(),key);
        } catch (Exception e) {

            throw new ClientException("用户名或密码错误");
        }
    }

    /**
     * 修改员工信息
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateId(Emp emp) {
        //员工用户名判重
        Emp emp1 = empMapper.selectIdEmp(emp.getId());
        if (!StrUtil.equals(emp1.getUsername(),emp.getUsername())){
            Integer count = empMapper.usernameCount(emp.getUsername());
            if (count>0){
                throw new ClientException(emp.getDeptName()+"用户名已存在,请更换");
            }
        }
        //手机号判重
        if(!StrUtil.equals(emp1.getPhone(),emp.getPhone())) {
            Integer count = empMapper.phoneCount(emp.getPhone());
            if (count>0){
                throw new ClientException(emp.getPhone()+"手机号已存在,请更换");
            }
        }
        // 修改员工员工信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
        //删除之前员工信息
        empExpMapper.deleteEmp(List.of(emp.getId()));
        //新增现在员工信息
        List<EmpExp> exprList = emp.getExprList();
        if (CollUtil.isNotEmpty(exprList)) {
            exprList.stream()
                    .peek(item -> item.setEmpId(emp.getId()))
                    .toList();
            empExpMapper.add(exprList);
        }

    }

    /**
     * 新增员工
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEmpAndExp(Emp emp) {
        /** 保存员工基本信息 */
        LocalDateTime now = LocalDateTime.now();
        emp.setPassword("456321");
        emp.setCreateTime(now);
        emp.setUpdateTime(now);
        log.info("EmpServiceImpl addEmpAndExp:{}", emp);
        empMapper.addEmpAndExp(emp);
        /** 为每条工作经历都补齐empid */
        List<EmpExp> exprList = emp.getExprList();
        if (CollUtil.isNotEmpty(exprList)) {
            exprList.stream()
                    .peek(item -> item.setEmpId(emp.getId()))
                    .toList();
            empExpMapper.add(exprList);
        }

    }
}
